package com.itbaizhan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @author spf
 * @date 2024/2/1
 * @time 20:52
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/index")
    public String index(){
        // 远程调用方法的主机名
        String hostName = "CLOUD-PROVIDER-PAYMENT";
        // 根据主机名获取实例
        List<ServiceInstance> instances = discoveryClient.getInstances(hostName);
        // 获取某台实例
        ServiceInstance serviceInstance = instances.get(0);
        // 获取uri
        URI uri = serviceInstance.getUri();
        // 远程调用具体的url
        String url = "/payment/index";
        System.out.println(uri + url);
        // 远程调用
        String forObject = restTemplate.getForObject(uri + url, String.class);
        return forObject;
    }

}
